import { deleteMeterApi, updateMeterApi } from "@/api/meter";
import { nextTick, ref } from "vue";
import { useMeterStore } from "@/stores/meter";

const meterStore = useMeterStore();

export function useMeterStructure(refreshCallback) {
  const dialogVisible = ref(false);
  const viewDialogVisible = ref(false);
  const currentMeter = ref(null);
  const parent_meter = ref(null);
  const loading = ref(false);
  const nodeDraggable = ref(false);

  //处理节点点击
  async function handleNodeClick(node) {
    if (node.id !== 1) {
      try {
        meterStore.setCurrentMeter(node.$$data);
        nextTick(() => {
          viewDialogVisible.value = true;
        });
      } catch (err) {
        console.error("处理节点点击失败:", err);
        ElMessage.error("加载数据失败");
      }
    }
  }

  // 处理节点添加
  function nodeAdd(node) {
    parent_meter.value = node;
    dialogVisible.value = true;
  }

  // 处理节点删除
  async function nodeDelete(node) {
    if (node.id === 1) {
      ElMessage.error("根节点不能删除");
      return;
    }

    try {
      await ElMessageBox.confirm("确认要删除该节点吗？", "提示", {
        type: "warning",
      });

      loading.value = true;
      const res = await deleteMeterApi([node.id]);

      if (res.code === 200) {
        ElMessage.success("删除成功");
        await meterStore.fetchMeterList();
      } else {
        throw new Error(res.message || "删除失败");
      }
    } catch (err) {
      if (err !== "cancel") {
        console.error(err);
        ElMessage.error(err.message || "删除失败");
      }
    } finally {
      loading.value = false;
    }
  }

  // 处理节点编辑
  function nodeEdit(node) {
    if (node.id === 1) {
      ElMessage.error("根节点不能编辑");
      return;
    }
    currentMeter.value = node;
    parent_meter.value = {
      id: node.parent_id,
      type: node.type,
    };
    dialogVisible.value = true;
  }

  // 处理拖拽结束
  async function handleDragEnd(data, pdata) {
    if (!nodeDraggable.value) return;

    try {
      await ElMessageBox.confirm("确认要保存此次拖拽更改吗？", "提示", {
        type: "warning",
      });

      await nodeDragEnd(data, pdata);
    } catch (err) {
      if (err !== "cancel") {
        console.error("拖拽更改失败", err);
      }
    } finally {
      handleDialogClose();
    }
  }

  // 执行拖拽更新
  async function nodeDragEnd(data, pdata) {
    loading.value = true;
    try {
      const res = await updateMeterApi({
        id: data.id,
        parent_id: pdata.id,
      });

      if (res.code === 200) {
        ElMessage.success("拖拽更改成功");
        await meterStore.fetchMeterList();
      } else {
        throw new Error(res.message || "拖拽更改失败");
      }
    } catch (err) {
      console.error(err);
      ElMessage.error(err.message || "拖拽更改失败");
    } finally {
      loading.value = false;
    }
  }

  // 统一处理弹窗关闭（无论成功还是取消都刷新）
  async function handleDialogClose() {
    dialogVisible.value = false;
    await meterStore.fetchMeterList(); // 强制刷新树图
    // 调用外部传入的刷新函数（如刷新读数等）
    if (refreshCallback && typeof refreshCallback === 'function') {
      await refreshCallback();
    }
    currentMeter.value = null;
    parent_meter.value = null;
  }

  // 处理弹窗成功
  async function handleDialogSuccess() {
    ElMessage.success("操作成功");
    await handleDialogClose();
  }

  return {
    dialogVisible,
    viewDialogVisible,
    currentMeter,
    parent_meter,
    loading,
    nodeDraggable,
    handleNodeClick,
    nodeAdd,
    nodeDelete,
    nodeEdit,
    handleDragEnd,
    handleDialogSuccess,
    handleDialogClose, // 新增统一关闭处理
  }
}